package com.adobe.apprise.aggregator
{
	import com.adobe.xml.syndication.generic.*;
	
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.html.HTMLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLStream;
	import flash.utils.ByteArray;

	public class Aggregator
	{
		public function getFeed(responder:AggregatorResponder, url:String):void
		{
			var req:URLRequest = getURLRequest(url);
			var stream:URLStream = getURLStream(responder);
			stream.addEventListener(Event.COMPLETE,
				function():void
				{
					var feedXml:XML;
					try
					{
						var xmlBytes:ByteArray = getDataFromStream(stream);
						feedXml = new XML(xmlBytes);
					}								
					catch (xmlError:Error)
					{
						var xmlErrorEvent:AggregatorEvent = new AggregatorEvent(AggregatorEvent.ERROR_EVENT);
						xmlErrorEvent.data = xmlError.message;
						responder.dispatchEvent(xmlErrorEvent);
						return;						
					}
					var feed:IFeed;
					try
					{
						feed = FeedFactory.getFeedByXML(feedXml);
					}
					catch (feedError:Error)
					{
						var feedErrorEvent:AggregatorEvent = new AggregatorEvent(AggregatorEvent.ERROR_EVENT);
						feedErrorEvent.data = feedError.message;
						responder.dispatchEvent(feedErrorEvent);
						return;						
					}
					var ae:AggregatorEvent = new AggregatorEvent(AggregatorEvent.FEED_EVENT);
					ae.data = feed;
					responder.dispatchEvent(ae);
				});
			stream.load(req);
		}
		
		// Private functions //
		
		private function getURLRequest(url:String):URLRequest
		{
			var req:URLRequest = new URLRequest(url);
			return req;
		}

		private function getURLStream(responder:AggregatorResponder):URLStream
		{
			var stream:URLStream = new URLStream();
			stream.addEventListener(IOErrorEvent.IO_ERROR,
				function(e:IOErrorEvent):void
				{
					responder.dispatchEvent(e);
				});
			stream.addEventListener(ProgressEvent.PROGRESS,
				function(e:ProgressEvent):void
				{
					responder.dispatchEvent(e);
				});
			stream.addEventListener(Event.COMPLETE,
				function(e:Event):void
				{
					responder.dispatchEvent(e);
				});
			stream.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS,
				function(e:HTTPStatusEvent):void
				{
					responder.dispatchEvent(e);
				});
			return stream;
		}

		private function getDataFromStream(stream:URLStream):ByteArray
		{
			var bytes:ByteArray = new ByteArray();
			stream.readBytes(bytes);
			return bytes;
		}
	}
}